﻿using System;
using System.Collections.Generic;
using Firefly.Framework.Components;
using Microsoft.Xna.Framework;

namespace Firefly.Framework.Collections
{
    public class ComponentCollection : List<IComponent>
    {
        public List<IUpdateableComponent> UpdateableComponents
        {
            get
            {
                List<IUpdateableComponent> components = new List<IUpdateableComponent>();

                foreach (IComponent c in this)
                {
                    if (c is IUpdateableComponent)
                    {
                        components.Add(c as IUpdateableComponent);
                    }
                }

                if (components.Count > 0)
                {
                    return components;
                }

                return null;
            }
        }

        public List<IDrawableComponent> DrawableComponents
        {
            get
            {
                List<IDrawableComponent> components = new List<IDrawableComponent>();

                foreach (IComponent c in this)
                {
                    if (c is IDrawableComponent)
                    {
                        components.Add(c as IDrawableComponent);
                    }
                }

                if (components.Count > 0)
                {
                    return components;
                }

                return null;
            }
        }

        public ComponentCollection()
        {
        }

        public void Update(GameTime gameTime)
        {
            List<IUpdateableComponent> components = UpdateableComponents;

            if (components != null)
            {
                components.Sort(new UpdateableComponentUpdateOrderComparer());

                foreach (IUpdateableComponent c in components)
                {
                    c.Update(gameTime);
                }
            }
        }

        public void Draw(GameTime gameTime)
        {
            List<IDrawableComponent> components = DrawableComponents;

            if (components != null)
            {
                components.Sort(new DrawableEntityDrawOrderComparer());

                foreach (IDrawableComponent c in components)
                {
                    c.Draw(gameTime);
                }
            }
        }

        public void LoadContent()
        {
            foreach (IComponent c in this)
            {
                if (c is IHasContent)
                {
                    (c as IHasContent).LoadContent();
                }
            }
        }

        public void UnloadContent()
        {
            foreach (IComponent c in this)
            {
                if (c is IHasContent)
                {
                    (c as IHasContent).UnloadContent();
                }
            }
        }
    }
}
